/*
 * Created on Nov 27, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package org.jugjobs.form;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

/**
 * @author rcook
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class PasswordActionForm extends ActionForm
{
    private String posting_password;
    public String getPosting_password() { return (posting_password); }
    public void setPosting_password(String s) { posting_password = s; }
    
    public void reset(ActionMapping mapping, HttpServletRequest request)
    {
    	posting_password = "";
    }
    
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)
    {
    	ActionErrors actionErrors = new ActionErrors();

    	HttpSession session = request.getSession();
		// this only all still works if we still have a session.
		// if they let the form sit until the session timed out, we won't get one here.
		if (session == null)
		{
			actionErrors.add("timeout", new ActionError("jugjobs.errors.possibleTimeout"));
		}
		else
		{	// if there's a password, compare against the password stored with job.
	    	if (posting_password != null && (!"".equals(posting_password)))
	    	{		// there's a password of some sort, see if it matches the one for the job.
		    		JobBean currentJobBean = (JobBean) session.getAttribute("currentJobBean");
		    		if (posting_password.equals(currentJobBean.getPosting_password()))
		    		{	session.setAttribute("AUTHENTICATED_FOR_JOB_NO", currentJobBean.getJob_number());
		    		}
		    		else
		    		{	actionErrors.add("password", new ActionError("jugjobs.jobpassword.incorrectPassword"));
		    		}
	    	}
	    	else
	    	{

				// There's no password: if there's an admin logged in let them edit this
				//    job anyway.
		    	if (session.getAttribute("ADMIN_LOGGED_IN") == null)
		    	{
			    	actionErrors.add("password", new ActionError("jugjobs.jobpassword.noPassword"));
		    	}
			}
		}
		
    	return actionErrors;
    }
    
} // end of PasswordActionForm